
package com.be.beadmin.basicData.impl;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelReader;
import com.be.beadmin.basicData.dto.output.MaterialInfoEx;
import com.be.beadmin.basicData.dto.output.MaterialInfoExcelEx;
import com.be.beadmin.basicData.entity.MaterialInfo;
import cn.hutool.core.util.ObjectUtil;
import com.be.beadmin.basicData.entity.MaterialInfo_;
import com.be.beadmin.basicData.utils.ExcelListener;
import com.be.beadmin.common.entity.PageEntity;
import com.be.beadmin.common.exception.BeadminException;
import com.be.beadmin.common.utils.JpaQueryBuilder;
import com.be.beadmin.common.utils.JpaSortBuilder;
import lombok.RequiredArgsConstructor;
import com.be.beadmin.basicData.mapper.MaterialInfoMapperEx;
import com.be.beadmin.basicData.repository.MaterialInfoRepository;
import com.be.beadmin.basicData.service.MaterialInfoService;
import com.be.beadmin.basicData.dto.input.MaterialInfoDto;
import com.be.beadmin.basicData.dto.output.MaterialInfoEx;
import com.be.beadmin.basicData.dto.input.MaterialInfoQueryCriteria;
import com.be.beadmin.basicData.mapper.MaterialInfoMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Order;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
* @description 服务实现
* @author cms
* @date 2023-12-07
**/
@Service
@RequiredArgsConstructor
public class MaterialInfoServiceImpl implements MaterialInfoService {

    @Autowired
    private  MaterialInfoRepository materialInfoRepository;
    @Autowired
    private  MaterialInfoMapper materialInfoMapper;
    @Autowired
    private  MaterialInfoMapperEx materialInfoExMapper;

    @Override
    public Page<MaterialInfoEx> getMaterialInfoByPage(PageEntity pageEntity) {
            Pageable pageable = PageRequest.of(
            pageEntity.getCurrent() -1,
            pageEntity.getPageSize());
            Page<MaterialInfo> page = materialInfoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> {
                    List<Predicate> list = new ArrayList<>();
                    Predicate pre1 =   JpaQueryBuilder.getPredicate(root, pageEntity.getFilters(), criteriaBuilder);
                    list.add(pre1);
                    Predicate pre2 = criteriaBuilder.equal(root.get(MaterialInfo_.delete), 0); //过滤为0
                    list.add(pre2);
                    Predicate[] p = new Predicate[list.size()];
                    List<Order> orders = new ArrayList<>();
                    if(pageEntity.getSorters() != null && pageEntity.getSorters().size() > 0) {
                        orders = JpaSortBuilder.getPredicate(root, pageEntity.getSorters(), criteriaBuilder);
                        criteriaQuery.orderBy(orders);
                    } else {
                        criteriaQuery.orderBy(criteriaBuilder.desc(root.get(MaterialInfo_.createTime).as(Date.class)));
                    }
                    return  criteriaBuilder.and(list.toArray(p));
                    }
                    , pageable);
            Page<MaterialInfoEx> page1 = page.map(materialInfoExMapper::toEntity);
            return page1;
    }

    @Override
    public void addMaterialInfo(MaterialInfoDto materialInfoDto) {
        MaterialInfo result = materialInfoRepository.findMaterialInfoByIdAndDelete(materialInfoDto.getId(), 0);
        if(ObjectUtil.isNotEmpty(result)) {
            throw new BeadminException("MaterialInfo不存在,请重新查询");
        }
        MaterialInfo materialExisted = materialInfoRepository.findMaterialInfoByMaterialCode(materialInfoDto.getMaterialCode());

        if (materialExisted != null){
            throw new BeadminException("该物料编码已存在");
        }
        MaterialInfo materialInfo = materialInfoMapper.toEntity(materialInfoDto);
        materialInfoRepository.save(materialInfo);
    }

    @Override
    public void updateMaterialInfo(MaterialInfoDto materialInfoDto) {
            MaterialInfo materialInfo = materialInfoRepository.findMaterialInfoById(materialInfoDto.getId());
            materialInfo = materialInfoMapper.toEntity(materialInfoDto);
            materialInfoRepository.save(materialInfo);
    }


    @Override
    public void delMaterialInfo(String id) {
        MaterialInfo materialInfo = materialInfoRepository.findMaterialInfoById(id);
        materialInfo.setDelete(1);
        materialInfoRepository.save(materialInfo);
    }

    @Override
    public void delMaterialInfos (List<String> ids) { }

    @Override
    public void uploadMaterialInfo(MultipartFile file) {
        ExcelListener<MaterialInfoExcelEx> excelListener = new ExcelListener<>();
        try{
            ExcelReader excelReader = EasyExcelFactory.read(file.getInputStream(),MaterialInfoExcelEx.class ,excelListener).headRowNumber(1).build();
            excelReader.readAll();
            excelReader.finish();
        }catch (IOException e ) {
            throw new BeadminException("解析失败");
        }

        List<MaterialInfoExcelEx> uploadDatas = excelListener.getDatas();
        List<String> storedList = materialInfoRepository.findMaterialInfoByDelete(0).stream().map(MaterialInfo::getMaterialCode).collect(Collectors.toList());

        uploadDatas.stream().map(MaterialInfoExcelEx::getMaterialCode).filter(storedList::contains).findAny().ifPresent(s -> {
            throw new BeadminException("【"+ s + "】"+"物料编码已存在");
        });

        List<MaterialInfo> entity = uploadDatas.stream().map(s -> {
            MaterialInfo t = new MaterialInfo();
            BeanUtils.copyProperties(s, t);
            return t;
        }).collect(Collectors.toList());

        materialInfoRepository.saveAll(entity);
    }

    @Override
    public MaterialInfo getMaterialInfo(String materialCode) {
        return materialInfoRepository.findMaterialInfoByMaterialCode(materialCode);
    }

    @Override
    public void insertMaterialInfo(MaterialInfo materialInfo) {
        materialInfoRepository.save(materialInfo);
    }

    @Override
    public List<MaterialInfo> getMaterialInfoByMaterialProperty(String materialProperty) {
        List<MaterialInfo>  materialInfoList= materialInfoRepository.findMaterialInfoByMaterialPropertyAndDelete(materialProperty,0);
        return materialInfoList;





    }

    @Override
    public String getMaterialNameByMaterialCode(String materialCode) {
        MaterialInfo materialInfo = materialInfoRepository.findMaterialInfoByMaterialCodeAndDelete(materialCode , 0);
        String materialName = materialInfo.getMaterialName();
        return materialName;
    }

    @Override
    public String getMaterialSpecByMaterialCode(String materialCode) {
        MaterialInfo materialInfo = materialInfoRepository.findMaterialInfoByMaterialCodeAndDelete(materialCode , 0);
        String materialSpec = materialInfo.getMaterialSpec();
        return materialSpec;
    }
}